from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, func
from typing import Optional, List, Dict
from datetime import datetime

from models.info_model import InfoPublishModel
from schemas.info_schema import (
    InfoPublishCreate, InfoPublishUpdate, InfoPublishQuery,
    InfoPublishInfo
)


# 模型转换方法添加type_id

def info_publish_model_to_dict(db_info: InfoPublishModel) -> dict:
    return {
        'type_id': db_info.type_id,  # 新增字段
        'id': db_info.id,
        'shop_id': db_info.shop_id,
        'tenant_id': db_info.tenant_id,
        'content': db_info.content,
        'info_type': db_info.info_type,
        'create_by': db_info.create_by,
        'update_by': db_info.update_by,
        'create_time': db_info.create_time,
        'update_time': db_info.update_time,
        'status': db_info.status
    }


class InfoPublishCRUD:
    """信息发布CRUD操作"""
    
    @staticmethod
    # 创建方法增加字段映射
    # 在创建方法中补充type_id
    @staticmethod
    def create_info(db: Session, info: InfoPublishCreate) -> dict:
        new_info = InfoPublishModel(
            type_id=info.type_id,  # 新增字段
            content=info.content,
            info_type=info.info_type,
            shop_id=info.shop_id,
            tenant_id=info.tenant_id,
            create_by=info.create_by,
            status=1  # 新创建的信息状态为有效
        )
        
        db.add(new_info)  # 修复变量名错误，从 db_info 改为 new_info
        db.commit()
        db.refresh(new_info)  # 同时需要修改这里的变量名
        
        return info_publish_model_to_dict(new_info)  # 返回时也使用正确的变量名
    
    
    @staticmethod
    def update_info(db: Session, info_id: str, info: InfoPublishUpdate) -> Optional[dict]:
        """更新信息发布记录"""
        db_info = db.query(InfoPublishModel).filter(
            InfoPublishModel.id == info_id
        ).first()
        
        if not db_info:
            return None
        
        # 更新字段
        if info.info_type is not None:
            db_info.info_type = info.info_type
        if info.content is not None:
            db_info.content = info.content
        if info.type_id is not None:  # 添加对type_id字段的更新处理
            db_info.type_id = info.type_id
        if info.status is not None:
            db_info.status = info.status
        if info.update_by is not None:
            db_info.update_by = info.update_by
        
        db.commit()
        db.refresh(db_info)
        
        return info_publish_model_to_dict(db_info)
    
    
    @staticmethod
    def get_info_by_id(db: Session, info_id: str) -> Optional[dict]:
        """根据ID获取信息发布记录"""
        db_info = db.query(InfoPublishModel).filter(
            InfoPublishModel.id == info_id
        ).first()
        
        if not db_info:
            return None
        
        return info_publish_model_to_dict(db_info)
    
    
    @staticmethod
    def get_infos(db: Session, query: InfoPublishQuery) -> Dict[str, any]:
        """查询信息发布记录列表"""
        # 构建查询条件
        conditions = []
        if query.shop_id:
            conditions.append(InfoPublishModel.shop_id == query.shop_id)
        if query.tenant_id:
            conditions.append(InfoPublishModel.tenant_id == query.tenant_id)
        if query.info_type:
            conditions.append(InfoPublishModel.info_type == query.info_type)
        if query.status is not None:
            conditions.append(InfoPublishModel.status == query.status)
        
        # 执行查询
        db_query = db.query(InfoPublishModel).filter(*conditions)
        
        # 计算总数
        total = db_query.count()
        
        # 分页
        offset = (query.pageIndex - 1) * query.pageSize
        db_infos = db_query.order_by(InfoPublishModel.create_time.desc()).offset(offset).limit(query.pageSize).all()
        
        # 转换为字典列表
        items = [info_publish_model_to_dict(info) for info in db_infos]
        
        return {
            'total': total,
            'items': items
        }
    
    
    @staticmethod
    def delete_info(db: Session, info_id: str) -> bool:
        """删除信息发布记录（软删除）"""
        db_info = db.query(InfoPublishModel).filter(
            InfoPublishModel.id == info_id
        ).first()
        
        if not db_info:
            return False
        
        db_info.status = 0
        db_info.update_time = datetime.now()
        
        db.commit()
        
        return True


# 补充查询过滤条件（示例）
@staticmethod
def get_infos(db: Session, query: InfoPublishQuery):
    filters = []
    if query.type_id:
        filters.append(InfoPublishModel.type_id == query.type_id)